//
//  EXObjectProxy.m
//  ORM
//
//  Created by PH on 21.12.09.
//  Copyright 2009-2010 Codesign. All rights reserved.
//

#import "EXObjectProxy.h"

@implementation EXObjectProxy

- (id)initWithObjectID:(NSString*)_objectID objectStore:(EXObjectStore*)_objectStore {
	if ((self = [super init])) {
		__objectID = [_objectID retain];
		__objectStore = _objectStore;
		__counter = 1;
	}
	return self;
}

- (BOOL)isContentDiscarded {
	return __object == nil;
}

- (void)discardContentIfPossible {
	if (__counter == 0) {
		[__object release];
		__object = nil;
	}
}

- (BOOL)beginContentAccess {
	__counter++;
	return YES;
}

- (void)endContentAccess {
	NSAssert(__counter > 0, @"Proxy counter is zero and proxy got endContentAccess");
	__counter--;
}

- (NSObject*)__object {
	if (__object == nil) __object = [[__objectStore objectWithObjectID: __objectID lazyCollections: YES] retain];
	return __object;
}

- (NSString*)__objectID {
	return __objectID;
}

- (BOOL)__isActivated {
	return __object != nil;
}

- (NSString*)className {
	return NSStringFromClass([[self __object] class]);
}

- (BOOL)isEqual:(id)object {
	return [[self __object] isEqual: object];
}

- (id)valueForUndefinedKey:(NSString*)key {
	return [[self __object] valueForUndefinedKey: key];
}

- (void)setValue:(id)value forUndefinedKey:(NSString*)key {
	[[self __object] setValue: value forUndefinedKey: key];
}

- (NSString*)description {
	id _object = [self __object];
	NSString* desc = [_object description];
	return [NSString stringWithFormat: @"(proxy) %@", desc];
}

- (BOOL)isKindOfClass:(Class)cls {
	return [[self __object] isKindOfClass: cls];
}

- (BOOL)isMemberOfClass:(Class)cls {
	return [[self __object] isMemberOfClass: cls];
}

/*- (void)encodeWithCoder:(NSCoder*)coder {
	[[self __object] encodeWithCoder: coder];
}*/

- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
	NSMethodSignature* signature = [super methodSignatureForSelector: selector];
	if (signature) return signature;
	signature = [[self __object] methodSignatureForSelector: selector];
	if (signature == nil) NSLog(@"The wrapped object doesn't recognize the forwarded selector");
	return signature;
}

- (void)forwardInvocation:(NSInvocation*)invocation {
	if ([__object respondsToSelector: [invocation selector]]) [invocation invokeWithTarget: __object];
	else [self doesNotRecognizeSelector: [invocation selector]];
}

- (void)dealloc {
	[__objectID release];
	[__object release];
	[super dealloc];
}

@end
